// Copyright 2019 The rhyme_lph Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Z [author] rhyme_lph
// z [email]  rhymelph@gmail.com
// A [github] https://github.com/rhymelph

import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/generated/l10n.dart';
import 'package:finance_app/src/common/app_colors.dart';
import 'package:finance_app/src/common/app_spaces.dart';
import 'package:finance_app/src/entities/account_entity.dart';
import 'package:finance_app/src/entities/bank_detail_record_item_entity.dart';
import 'package:finance_app/src/entities/bank_reconciliation_entity.dart';
import 'package:finance_app/src/utils/cash_utils.dart';
import 'package:finance_app/src/utils/date_time_utils.dart';
import 'package:finance_app/src/widgets/button/add_button.dart';
import 'package:finance_app/src/widgets/button/normal_float_text_button.dart';
import 'package:finance_app/src/widgets/common/normal_table_pro.dart';
import 'package:finance_app/src/widgets/common_app_bar.dart';
import 'package:finance_app/src/widgets/select/reconcile_radio.dart';
import 'package:flutter/material.dart';
import 'package:finance_app/src/provider/all_reports/bank_reconciliation/reconcile_account_detail_provider.dart';
import 'package:finance_app/src/router_gen/router_meta.dart';
import 'package:tuple/tuple.dart';
export 'package:finance_app/src/entities/account_entity.dart';
export 'package:finance_app/src/entities/bank_reconciliation_entity.dart';

@RouterMeta(paramName: "reconcileAccountDetailPage")
class ReconcileAccountDetailPage extends StatefulWidget {
  final BankReconciliationEntity bank;
  final AccountEntity currentAccount;
  final String title;
  final String closingDate;

  const ReconcileAccountDetailPage({
    Key key,
    this.bank,
    this.title,
    this.currentAccount,
    this.closingDate,
  }) : super(key: key);

  @override
  _ReconcileAccountDetailPageState createState() =>
      _ReconcileAccountDetailPageState();
}

class _ReconcileAccountDetailPageState extends State<ReconcileAccountDetailPage>
    with
        PagePresenter<ReconcileAccountDetailPage,
            ReconcileAccountDetailProvider> {
  @override
  PreferredSizeWidget get appBar => getDefaultAppBar(
        title: widget.title,
      );

  @override
  void initState() {
    provider.closingDate = widget.closingDate;
    provider.bank = widget.bank;
    provider.id = widget.bank.id;
    provider.title = widget.title;

    provider.realDifference = widget.bank.difference;
    super.initState();
  }

  @override
  Widget get buildEmptyWidget => Stack(
        children: [
          ColoredBox(
            color: Colors.white,
            child: Column(
              children: [
                buildNoFileTopWidget(),
                Expanded(child: super.buildEmptyWidget),
              ],
            ),
          ),
          _buildBottomBar(),
        ],
      );

  @override
  Widget get buildWidget => Stack(
        children: [
          ColoredBox(
            color: Colors.white,
            child: Column(
              children: [
                buildNoFileTopWidget(),
                AppSpaces.grayH05,
                Expanded(
                  child: listBuilder<List<BankDetailRecordItemEntity>>(
                    selector: (_, __) => List.from(__.data),
                    builder: (BuildContext context,
                            List<BankDetailRecordItemEntity> value,
                            Widget child) =>
                        ListView.separated(
                      itemBuilder: _buildNoFileItems,
                      itemCount: value.length + 1,
                      separatorBuilder: (BuildContext context, int index) {
                        return Container();
                      },
                    ),
                  ),
                ),
              ],
            ),
          ),
          _buildBottomBar(),
        ],
      );

  Container _buildBankTitleBar({String statementBalance, String difference}) {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: getDp(25), vertical: getDp(20)),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                S.current.statement_balance,
                style: TextStyle(
                  color: aceDarkGrayColor,
                  fontSize: getSp(16),
                  fontWeight: FontWeight.w400,
                  height: 1,
                ),
              ),
              SizedBox(
                height: getDp(6),
              ),
              Text(
                statementBalance,
                style: TextStyle(
                  color: aceBlackColor,
                  fontSize: getSp(18),
                  fontWeight: FontWeight.w700,
                  height: 1,
                ),
              ),
            ],
          ),
          Column(
            crossAxisAlignment: CrossAxisAlignment.end,
            children: [
              Text(
                S.current.difference,
                style: TextStyle(
                  color: aceDarkGrayColor,
                  fontSize: getSp(16),
                  fontWeight: FontWeight.w400,
                  height: 1,
                ),
              ),
              SizedBox(
                height: getDp(6),
              ),
              Text(
                difference,
                style: TextStyle(
                  color: aceBlackColor,
                  fontSize: getSp(18),
                  fontWeight: FontWeight.w700,
                  height: 1,
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget buildNoFileTopWidget() => Column(
        children: [
          listBuilder<Tuple2<String, String>>(
            selector: (_, __) => Tuple2(widget.bank.statementBalance,
                CashUtils.formatCashAmount(__.difference)),
            builder: (BuildContext context, Tuple2<String, String> value,
                    Widget child) =>
                _buildBankTitleBar(
              statementBalance:
                  '${widget.currentAccount.currencyCode} ${value.item1}',
              difference:
                  '${widget.currentAccount.currencyCode} ${value.item2}',
            ),
          ),
          NormalTableProTitleItem(
            title: S.current.book_records,
            padding: EdgeInsets.symmetric(
              horizontal: getDp(25),
              vertical: getDp(5),
            ),
          ),
          AppSpaces.h20,
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              listBuilder<int>(
                selector: (_, __) => __.selectReconcileList.length,
                builder: (BuildContext context, int value, Widget child) =>
                    PressedOpacityButton(
                  onPressed: value > 0
                      ? provider.onDeselectAllReconcile
                      : provider.onSelectAllReconcile,
                  padding: EdgeInsets.only(left: getDp(25)),
                  child: Text(
                    value > 0 ? S.current.deselect_all : S.current.select_all,
                    style: TextStyle(
                      color: aceBlueColor,
                      fontSize: getSp(16),
                      fontWeight: FontWeight.w700,
                      height: 14 / 16,
                    ),
                  ),
                ),
              ),
              Padding(
                padding: EdgeInsets.only(right: getDp(25)),
                child: AddButton(
                  title: S.current.add_new,
                  onTap: provider.onAddNewReconcile,
                ),
              )
            ],
          ),
          AppSpaces.h20,
        ],
      );

  Widget _buildNoFileItems(BuildContext context, int index) {
    if (provider.data.length == index) return Container();
    return listBuilder<Tuple2<bool, BankDetailRecordItemEntity>>(
      selector: (_, __) => Tuple2(
          __.selectReconcileList.firstWhere(
                  (element) => element.id == __.data[index].id,
                  orElse: () => null) !=
              null,
          __.data[index]),
      builder: (BuildContext context,
              Tuple2<bool, BankDetailRecordItemEntity> value, Widget child) =>
          PressedOpacityButton(
        onPressed: () => provider.onSelectReconcile(value.item2),
        child: ReconcileCheckBox(
          isSelect: value.item1,
          name: value.item2.name,
          code: value.item2.number,
          type: value.item2.flowType,
          datetime:
              DateTimeUtils.formatDateTimeString(value.item2.issuedAt, true),
          amount: value.item2.total,
        ),
      ),
    );
  }

  Widget _buildBottomBar() => Positioned(
        bottom: MediaQuery.of(context).padding.bottom + getDp(32),
        left: 0,
        right: 0,
        child: Center(
          child: listBuilder<bool>(
            selector: (_, __) => __.difference == 0,
            builder: (BuildContext context, bool value, Widget child) =>
                NormalFloatTextButton(
              title: S.current.reconcile,
              onTap: value == true ? provider.onReconcile : null,
            ),
          ),
        ),
      );
}
